<template>
  <div id="caclResult">
    <Breadcrumb content="核算结果" />
    <div class="bodyContent">
      <Splitpanes class="area">
        <Pane size="30">
          <vxe-toolbar perfect>
            <template #buttons>
              <div class="smallToolTitle">核算批次</div>
              <vxe-input v-model="batchSearchform.searchValue" type="text" clearable class="vxeInputSearch" placeholder="关键字查询"></vxe-input>
              <vxe-button type="text" icon="vxe-icon-refresh" class="button-blue" content="刷新" @click="handleBatchList"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新增" @click="handleAdd()"></vxe-button>
              <!--              <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="handleBatchDelete"></vxe-button>-->
            </template>
          </vxe-toolbar>

          <div class="calcBatchTableBox">
            <vxe-table ref="calcBatchTableRef" @current-change="rowClick" class="mytable-scrollbar" border align="left" :keep-source="true" :data="batchList" :row-config="{ isCurrent: true, isHover: true }" resizable show-overflow height="auto">
              <vxe-column type="checkbox" align="center" width="26"></vxe-column>
              <vxe-column type="seq" title="序号" align="center" width="30"></vxe-column>
              <vxe-column field="batchCode" title="批次编码"></vxe-column>
              <vxe-column field="batchName" title="批次名称"></vxe-column>
              <vxe-column field="startDate" title="开始日期"></vxe-column>
              <vxe-column field="endDate" title="结束日期"></vxe-column>
              <vxe-column title="操作" fixed="right">
                <template #default="{ row }">
                  <vxe-button type="text" status="primary" icon="vxe-icon-edit" circle @click.native="editDictDialog(row)" class="spanIcon"></vxe-button>
                  <vxe-button type="text" status="danger" icon="vxe-icon-delete" circle @click.native="handleBatchDelete(row)" class="spanIcon"></vxe-button>
                </template>
              </vxe-column>
            </vxe-table>
          </div>

          <el-dialog title="核算批次" @close="handleFormClosed" v-model="dialogFormVisible" :modal-append-to-body="false" :close-on-click-modal="false" width="400px">
            <el-form ref="calcBatchFormRef" :model="form" :rules="dialogFormRules" :inline-message="true">
              <el-form-item prop="batchName" label="批次名称" :label-width="formLabelWidth">
                <el-input v-model="batchSearchform.batchName" autocomplete="off" clearable></el-input>
              </el-form-item>
              <el-form-item prop="ruleName" label="批次日期" :label-width="formLabelWidth">
                <el-date-picker v-model="batchSearchform.separator" type="daterange" range-separator="To" start-placeholder="Start date" format="YYYY-MM-DD" value-format="YYYY-MM-DD" end-placeholder="End date" size="small" />
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer justify-end flex">
              <el-button type="primary" @click="handleSaveBatch()">保 存</el-button>
              <el-button @click="handleFormClosed()">取 消</el-button>
            </div>
          </el-dialog>
        </Pane>
        <Pane size="70">
          <vxe-toolbar perfect>
            <template #buttons>
              <!-- <div class="datePickerDiv">
                <el-date-picker v-model="searchForm.separator" type="daterange" range-separator="To" start-placeholder="Start date" format="YYYY-MM-DD" value-format="YYYY-MM-DD" end-placeholder="End date" size="small" />
              </div> -->
              <vxe-button type="text" icon="vxe-icon-refresh" class="button-blue" content="刷新" @click="getCaclResultList" :loading="showLoading"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="计算" @click="buildData()"></vxe-button>
              <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="handleDelete"></vxe-button>
            </template>
          </vxe-toolbar>
          <div class="caclResultTableBox">
            <vxe-table ref="caclResultTableRef" :loading="showLoading" class="mytable-scrollbar" border align="left" height="auto" :keep-source="true" :data="calcDataBaseList" :row-config="{ isCurrent: true, isHover: true }" resizable show-overflow>
              <vxe-column type="checkbox" align="center" width="26"></vxe-column>
              <vxe-column type="seq" title="序号" align="center" width="30"></vxe-column>
              <vxe-column field="formulaCode" title="公式编码" width="60"></vxe-column>
              <vxe-column field="formulaName" title="公式名称"></vxe-column>
              <vxe-column field="userCode" title="用户编号" width="60"></vxe-column>
              <vxe-column field="userName" title="用户名称"></vxe-column>
              <vxe-column field="startDate" title="开始时间"> </vxe-column>
              <vxe-column field="endDate" title="结束时间"> </vxe-column>
              <vxe-column field="resultValue" title="核算结果"> </vxe-column>
              <vxe-column field="calcUser" title="核算人"> </vxe-column>
              <vxe-column field="isConfirm" title="是否确认"> </vxe-column>
              <vxe-column field="confirmDate" title="确认时间"> </vxe-column>
              <vxe-column field="confirmUser" title="确认人"> </vxe-column>
            </vxe-table>
          </div>
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>

<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示信息

// 定义变量区 ==========
let { proxy }: any = getCurrentInstance();
//根据关键字搜索
let searchForm = reactive({
  keyWord: '',
  separator: ''
});

let batchSearchform = reactive({
  id: null,
  searchValue: '',
  batchName: '',
  separator: ''
});
const calcDataBaseList = reactive([]); //表格数据
let showLoading = ref(false); //表格加载状态
let currentRowInfo = reactive({
  id: '',
  batchCode: '',
  startDate: '',
  endDate: ''
});

// 方法定义区 =====================================
onMounted(() => {
  handleBatchList();
  getCaclResultList();
});

// 获取左侧列表信息
function getCaclResultList() {
  calcDataBaseList.length = 0;
  showLoading.value = true;
  const url = '/wk/calc/result/getCalcResultList';
  proxy.$http
    .get(url, { params: { batchId: currentRowInfo.id } })
    .then((res: any) => {
      if (res.data) {
        calcDataBaseList.push(...res.data);
        const $xTable = proxy.$refs.caclResultTableRef as any;
        if ($xTable) {
          $xTable.setCurrentRow(calcDataBaseList[0]);
        }
        showLoading.value = false;
      }
    })
    .catch((err: any) => {
      showLoading.value = false;
      proxy.$alert(err, '提示');
    });
}

// 生成数据
function buildData() {
  const url = '/wk/calc/result/buildData';
  let separator = [];
  separator.push(currentRowInfo.startDate);
  separator.push(currentRowInfo.endDate);
  let obj = {
    dates: separator,
    batchId: currentRowInfo.id,
    batchCode: currentRowInfo.batchCode
  };
  proxy.$http
    .post(url, obj)
    .then((res: any) => {
      if (res.data) {
        getCaclResultList();
        VxeMessage('数据执行成功', VxeNotifyType.success);
      }
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

// 删除
function handleDelete() {
  const $xTable = proxy.$refs.caclResultTableRef as any;
  const selectRows = $xTable.getCheckboxRecords();
  if (selectRows.length <= 0) {
    VxeMessage('请先选中要删除的项', VxeNotifyType.warning);
    return;
  }
  proxy
    .$confirm('确定删除此项？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then((type) => {
      if (type === 'confirm') {
        let ids = selectRows.map((item) => item.id);
        const url = '/wk/calc/result/deleteCalcResult';
        proxy.$http
          .post(url, ids)
          .then((res: any) => {
            if (res.status.code === 1) {
              VxeMessage('删除成功', VxeNotifyType.success);
              getCaclResultList();
            } else {
              VxeMessage('删除失败', VxeNotifyType.error);
            }
          })
          .catch((err) => {
            VxeMessage(err.response.data.status.msg, VxeNotifyType.error);
          });
      }
    });
}

const dialogFormVisible = ref(false);

function handleAdd() {
  dialogFormVisible.value = true;
  batchSearchform.id = null;
  batchSearchform.batchName = null;
  batchSearchform.separator = null;
}

function handleFormClosed() {
  dialogFormVisible.value = false;
}

function handleSaveBatch() {
  console.log(JSON.stringify(batchSearchform));

  if (batchSearchform.id === null) {
    const url = '/wk/calc/batch/add';
    const user = {
      batchName: batchSearchform.batchName,
      dates: batchSearchform.separator
    };
    proxy.$http
      .post(url, user)
      .then((res: any) => {
        VxeMessage('新增成功', VxeNotifyType.success);
        handleFormClosed();
        handleBatchList();
      })
      .catch((err: any) => {
        VxeMessage('新增失败', VxeNotifyType.error);
      });
  } else {
    // 修改用户
    const url = '/wk/calc/batch/update';
    const user = {
      id: batchSearchform.id,
      batchName: batchSearchform.batchName,
      dates: batchSearchform.separator
    };
    proxy.$http
      .post(url, user)
      .then((res: any) => {
        VxeMessage('修改成功', VxeNotifyType.success);
        handleFormClosed();
        handleBatchList();
      })
      .catch((err: any) => {
        VxeMessage('修改失败', VxeNotifyType.error);
      });
  }
}

let batchList: any = reactive([]);

function handleBatchList() {
  batchList.length = 0;
  const url = '/wk/calc/batch/page';
  const params = {
    searchValue: batchSearchform.searchValue
  };
  proxy.$http
    .get(url, {params: params})
    .then((res: any) => {
      batchList.push(...res.data);
      const $xTable = proxy.$refs.calcBatchTableRef as any;
      if ($xTable) {
        $xTable.setCurrentRow(batchList[0]);
      }
      rowClick({ row: batchList[0] });
    })
    .catch((err: any) => {
      // VxeMessage('获取列表失败',VxeNotifyType.error)
    });
}
function handleBatchDelete(row: any) {
  proxy
    .$confirm('确定删除此字段？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(async () => {
      const url = '/wk/calc/batch/delete';
      proxy.$http.post(url, row).then((res: any) => {
        if (res.status.code === 1) {
          handleBatchList();
          VxeMessage('删除成功', VxeNotifyType.success);
        } else {
          VxeMessage(res.status.msg, VxeNotifyType.error);
        }
      });
    })
    .catch((err: any) => {
      // VxeMessage(err, VxeNotifyType.error);
    });
}

function editDictDialog(row: any) {
  dialogFormVisible.value = true;
  batchSearchform.id = row.id;
  batchSearchform.batchName = row.batchName;
  const dateList = [];
  dateList.push(row.startDate);
  dateList.push(row.endDate);
  batchSearchform.separator = dateList;
}
//给最右侧传值
function rowClick({ row }: any) {
  Object.assign(currentRowInfo, row);
  getCaclResultList();
}
</script>

<style lang="scss" scoped>
#caclResult {
  height: 100%;
  .bodyContent {
    height: calc(100% - 60px);
    // 附加按钮间距
    .button-blue,
    .button-red {
      margin: 5px 0 5px 5px;
    }
    .area {
      background-color: $base-white;
      .calcBatchTableBox {
       height: calc(100% - 40px);
      }
      .datePickerDiv {
      width: 370px;
      margin-right: 10px;
      }
      .caclResultTableBox {
      height: calc(100% - 40px);
      }
    }
  }
}
</style>
